package org.example.intercepor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.awt.desktop.PreferencesHandler;
import java.util.UUID;

public class TraceLogInterceptor implements HandlerInterceptor {

    private static final String TRACE_ID = "TRACE_ID";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //生成追踪id,如果客户端传入了追踪id,则使用客户端传入的追踪ID,否则使用默认的ULID生成

        String tid = UUID.randomUUID().toString();

        if(StringUtils.hasLength(request.getHeader(TRACE_ID))){
            tid = request.getHeader(TRACE_ID);
        }
        //将追踪的id放入到mdc中
        MDC.put(TRACE_ID, tid);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //请求完成后，从MDC中清空
        MDC.remove(TRACE_ID);
    }
}
